#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, hashlib, os, random, urllib, urllib2
from datetime import *

class Chaojiying_Client(object):

	"""
	普通POST
	"""
    def http_request(self, url, paramDict):
        post_content = ''
        for key in paramDict:
            post_content = post_content + '%s=%s&'%(key,paramDict[key])
        post_content = post_content[0:-1]
        #print post_content
        req = urllib2.Request(url, data=post_content)
        req.add_header('Content-Type', 'application/x-www-form-urlencoded')
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())  
        response = opener.open(req, post_content)  
        return response.read()

	"""
	文件上传POST
	"""	
    def http_upload_image(self, url, paramKeys, paramDict, filebytes):
        timestr = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        boundary = '------------' + hashlib.md5(timestr).hexdigest().lower()
        boundarystr = '\r\n--%s\r\n'%(boundary)
        
        bs = b''
        for key in paramKeys:
            bs = bs + boundarystr.encode('ascii')
            param = "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s"%(key, paramDict[key])
            #print param
            bs = bs + param.encode('utf8')
        bs = bs + boundarystr.encode('ascii')
        
        header = 'Content-Disposition: form-data; name=\"userfile\"; filename=\"%s\"\r\nContent-Type: image/gif\r\n\r\n'%('sample')
        bs = bs + header.encode('utf8')
        
        bs = bs + filebytes
        tailer = '\r\n--%s--\r\n'%(boundary)
        bs = bs + tailer.encode('ascii')
        
        import requests
        headers = {'Content-Type':'multipart/form-data; boundary=%s'%boundary,
                   'Connection':'Keep-Alive',
                   'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
                   }
        response = requests.post(url, params='', data=bs, headers=headers)
        return response.text

	"""
	暂未用到
	"""
	def arguments_to_dict(args):
		argDict = {}
		if args is None:
			return argDict
		
		count = len(args)
		if count <= 1:
			print 'exit:need arguments.'
			return argDict
		
		for i in [1,count-1]:
			pair = args[i].split('=')
			if len(pair) < 2:
				continue
			else:
				argDict[pair[0]] = pair[1]

		return argDict
    
    


if __name__ == '__main__':
    client = Chaojiying_Client()
    while 1:
        paramDict = {}
        result = ''
        act = raw_input('Action:')
		
        if cmp(act, 'info') == 0: 
            paramDict['user'] = raw_input('user:')
            paramDict['pass'] = raw_input('pass:')
            result = client.http_request('http://upload.chaojiying.net/Upload/GetScore.php', paramDict)
			
        elif cmp(act, 'reg') == 0:
            paramDict['user'] = raw_input('user:')
            paramDict['pass'] = raw_input('pass:')
            result = client.http_request('http://upload.chaojiying.net/Upload/UserReg.php', paramDict)
			
        elif cmp(act, 'pay') == 0:
            paramDict['user'] = raw_input('user:')
            paramDict['card'] = raw_input('card:')
            result = client.http_request('http://upload.chaojiying.net/Upload/UserPay.php', paramDict)
			
        elif cmp(act, 'report') == 0:
            paramDict['user'] = raw_input('user:')
            paramDict['pass'] = raw_input('pass:')
            paramDict['id'] = raw_input('id:')
			paramDict['softid'] = raw_input('softid:')
            result = client.http_request('http://upload.chaojiying.net/Upload/ReportError.php', paramDict)
			
        elif cmp(act, 'upload') == 0:
            paramDict['user'] = raw_input('user:')
            paramDict['pass'] = raw_input('pass:')
            paramDict['softid'] = raw_input('softid:')
            paramDict['codetype'] = raw_input('codetype:')
            paramKeys = ['user',
                 'pass',
                 'softid',
                 'codetype'
                ]
            import Image
            imagePath = raw_input('Image Path:')
            img = Image.open(imagePath)
            if img is None:
                print 'get file error!'
                continue
            img.save("ccc.gif", format="gif")
            filebytes = open("ccc.gif", "rb").read()
            result = client.http_upload_image("http://upload.chaojiying.net/Upload/Processing.php", paramKeys, paramDict, filebytes)
        
        elif cmp(act, 'help') == 0:
            print 'info'
            print 'reg'
            print 'pay'
            print 'report'
            print 'upload'
            print 'help'
            print 'exit'
        elif cmp(act, 'exit') == 0:
            break
        
        print result